package com.sayice.coursetable.logic.utils;

import androidx.annotation.NonNull;

import com.sayice.coursetable.logic.network.CourseService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;

/**
 * 网络工具类
 */
public abstract class NetUtils {
    /**
     * 获取设置了超时时间的 OkHttpClient 对象
     *
     * @param maxTime 超时时间（单位：秒）
     */
    public static OkHttpClient getTimeOutHttpClient(int maxTime) {
        return new OkHttpClient.Builder()
                .connectTimeout(maxTime, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 获取 OkHttpClient 对象
     */
    public static OkHttpClient getHttpClient() {
        return new OkHttpClient.Builder()
                .cookieJar(new LocalCookieJar())
                .build();
    }

    /**
     * 通过正则表达式在字符串中搜索指定字段
     *
     * @param data  字符串
     * @param regex 待搜索字段的正则表达式
     * @return 返回匹配到的第一个字段
     */
    public static String getField(String data, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(data);
        if (m.find()) {
            return m.group(1);
        }
        return "";
    }

    private static class LocalCookieJar implements CookieJar {
        private final List<Cookie> cookies = new ArrayList<>();

        @NonNull
        @Override
        public List<Cookie> loadForRequest(@NonNull HttpUrl url) {
            return cookies;
        }

        @Override
        public void saveFromResponse(@NonNull HttpUrl url, @NonNull List<Cookie> cookies) {
            this.cookies.addAll(cookies);
        }
    }
}
